'use client'

import { useState, useEffect, forwardRef, useImperativeHandle } from 'react'
import { StarDisplay } from '@/components/ui/star-rating'
import { User, MessageCircle } from 'lucide-react'
import { type StoredReview } from '@/lib/database'

interface ReviewListProps {
  toolId: string
}

export interface ReviewListRef {
  refreshReviews: () => void
}

export const ReviewList = forwardRef<ReviewListRef, ReviewListProps>(({ toolId }, ref) => {
  const [reviews, setReviews] = useState<StoredReview[]>([])
  const [loading, setLoading] = useState(true)
  const [error, setError] = useState<string | null>(null)
  const [sortBy, setSortBy] = useState<'newest' | 'oldest' | 'highest' | 'lowest'>('newest')

  useEffect(() => {
    fetchReviews()
  }, [toolId])

  useImperativeHandle(ref, () => ({
    refreshReviews: fetchReviews
  }))

  const fetchReviews = async () => {
    try {
      setLoading(true)
      const response = await fetch(`/api/tools/${toolId}/reviews`)
      const result = await response.json()

      if (response.ok) {
        setReviews(result.data || [])
      } else {
        setError(result.error || '获取评价失败')
      }
    } catch (error) {
      setError('网络错误，请重试')
    } finally {
      setLoading(false)
    }
  }

  const averageRating = reviews.length > 0
    ? reviews.reduce((sum, review) => sum + review.rating, 0) / reviews.length
    : 0

  // 排序评论
  const sortedReviews = [...reviews].sort((a, b) => {
    switch (sortBy) {
      case 'newest':
        return new Date(b.createdAt).getTime() - new Date(a.createdAt).getTime()
      case 'oldest':
        return new Date(a.createdAt).getTime() - new Date(b.createdAt).getTime()
      case 'highest':
        return b.rating - a.rating
      case 'lowest':
        return a.rating - b.rating
      default:
        return 0
    }
  })

  if (loading) {
    return (
      <div className="space-y-4">
        {Array.from({ length: 3 }).map((_, i) => (
          <div key={i} className="animate-pulse">
            <div className="flex items-start gap-3 p-4 bg-gray-50 rounded-lg">
              <div className="h-10 w-10 bg-gray-200 rounded-full"></div>
              <div className="flex-1">
                <div className="h-4 bg-gray-200 rounded w-1/4 mb-2"></div>
                <div className="h-3 bg-gray-200 rounded w-full mb-2"></div>
                <div className="h-3 bg-gray-200 rounded w-3/4"></div>
              </div>
            </div>
          </div>
        ))}
      </div>
    )
  }

  if (error) {
    return (
      <div className="text-center py-8">
        <MessageCircle className="h-12 w-12 text-gray-400 mx-auto mb-4" />
        <p className="text-gray-500">{error}</p>
      </div>
    )
  }

  return (
    <div className="space-y-6">
      {/* 评价统计 */}
      {reviews.length > 0 && (
        <div className="bg-gray-50 rounded-lg p-4">
          <div className="flex items-center justify-between">
            <div className="flex items-center gap-3">
              <StarDisplay rating={averageRating} size="md" showValue />
              <span className="text-sm text-gray-600">
                基于 {reviews.length} 条评价
              </span>
            </div>

            {reviews.length > 1 && (
              <select
                value={sortBy}
                onChange={(e) => setSortBy(e.target.value as any)}
                className="px-3 py-1 border border-gray-300 rounded-md text-sm focus:ring-2 focus:ring-blue-500 focus:border-blue-500"
              >
                <option value="newest">最新评价</option>
                <option value="oldest">最早评价</option>
                <option value="highest">评分最高</option>
                <option value="lowest">评分最低</option>
              </select>
            )}
          </div>
        </div>
      )}

      {/* 评价列表 */}
      {reviews.length === 0 ? (
        <div className="text-center py-8">
          <MessageCircle className="h-12 w-12 text-gray-400 mx-auto mb-4" />
          <p className="text-gray-500">暂无评价</p>
          <p className="text-sm text-gray-400 mt-1">成为第一个评价此工具的用户</p>
        </div>
      ) : (
        <div className="space-y-4">
          {sortedReviews.map((review) => (
            <div key={review.id} className="bg-white border border-gray-200 rounded-lg p-4">
              <div className="flex items-start gap-3">
                {/* 用户头像 */}
                <div className="h-10 w-10 bg-gradient-to-br from-blue-50 to-indigo-100 rounded-full flex items-center justify-center flex-shrink-0">
                  {review.user.avatar ? (
                    <img 
                      src={review.user.avatar} 
                      alt={review.user.name}
                      className="h-10 w-10 rounded-full object-cover"
                    />
                  ) : (
                    <User className="h-5 w-5 text-blue-400" />
                  )}
                </div>

                {/* 评价内容 */}
                <div className="flex-1 min-w-0">
                  <div className="flex items-center justify-between mb-2">
                    <div className="flex items-center gap-3">
                      <h4 className="font-medium text-gray-900">{review.user.name}</h4>
                      <StarDisplay rating={review.rating} size="sm" showValue={false} />
                    </div>
                    <time className="text-xs text-gray-500">
                      {new Date(review.createdAt).toLocaleDateString()}
                    </time>
                  </div>
                  
                  <p className="text-gray-700 text-sm leading-relaxed">
                    {review.comment}
                  </p>
                </div>
              </div>
            </div>
          ))}
        </div>
      )}
    </div>
  )
})

ReviewList.displayName = 'ReviewList'
